package com.qf.admin.loginFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

//@WebFilter("/admin/*")
public class LoginFilter  implements Filter {
    private List<String> staticResources = Arrays.asList(".js", ".css","gif",
            ".otf", ".jpg", ".png", ".eot", ".svg", ".ttf", ".woff", ".woff2");



    // 判断uri中是否包含静态的资源
    private boolean isContainsStaticResource(String uri) {
        for(String staticResource: staticResources) {
            if(uri.endsWith(staticResource)) {
                return true;
            }
        }
        return false;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String uri = req.getRequestURI(); //获取uri:
        //判断用户是否存在,有bug
        Object checkUser = req.getSession().getAttribute("adminUser");
        if (checkUser != null) {
           chain.doFilter(request, response);
            return;
        }


        if (uri.contains("admin/loginAdmin.jsp")|| isContainsStaticResource(uri)){
            chain.doFilter(req, resp);
            return;
        }

            resp.sendRedirect("loginAdmin.jsp");
    }

    @Override
    public void destroy() {

    }
}
